<template>
  <div class="ccui-app-container">
    <div class="ccui-advanced-search-wrapper ccui-clearfix">
      <el-search
        :formProp="formData"
        @search="search"
        :isShowSearch="isShowSearch"
        class="ccui-highsearch"
        :selectClear="true"
      >
        <div class="ccui-tab-wrapper">
          <el-button
            :type="isActive === index ? 'table-top-active' : 'table-top'"
            size="mini"
            v-for="(item, index) in focuses"
            :key="index"
            @click="tabChange(item.focus)"
          >
            <template v-if="item.focus === 'All'"
              >全部</template
            >
            <template v-if="item.focus === 'Submit'">待提交</template>
            <template v-else-if="item.focus === 'Approval'">审批中({{ totalNum || 0 }})</template>
            <template v-else-if="item.focus === 'ApprovalTurn'"
              >审批退回</template
            >
          </el-button>
        </div>
        <div class="ccui-extend-btn">
          <el-button
            size="mini"
            type="primary-icon-big"
            @click="handleGoNew"
            icon="icon-ccui-add-sup"
            >新增</el-button
          >
        </div>
        <template slot="search">
          <el-input
            v-model="formData.exwarehouseName"
            clearable
            searchLabel="出库单名称"
            placeholder="请输入出库单名称模糊查询"
            @blur="handleTrim('exwarehouseName')"
          ></el-input>
          <el-input
            v-model="formData.exwarehouseCode"
            clearable
            searchLabel="出库单编号"
            placeholder="请输入出库单编号模糊查询"
            @blur="handleTrim('exwarehouseCode')"
          ></el-input>
          <el-input
            v-model="formData.reportInOrgName"
            clearable
            searchLabel="填报单位"
            placeholder="请输入填报单位模糊查询"
            @blur="handleTrim('reportInOrgName')"
          ></el-input>
          <el-input
            v-model="formData.warehouseName"
            clearable
            searchLabel="仓库"
            placeholder="请输入仓库模糊查询"
            @blur="handleTrim('warehouseName')"
          ></el-input>
          <el-date-picker
            v-model="formData.reportTime"
            clearable
            searchLabel="编制日期"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </template>
        <!-- 表单高级搜索 -->
        <el-input
          v-model="formData.exwarehouseName"
          clearable
          searchLabel="出库单名称"
          placeholder="请输入出库单名称模糊查询"
          @blur="handleTrim('exwarehouseName')"
          slot="searchItem1"
        ></el-input>
        <el-input
          v-model="formData.exwarehouseCode"
          clearable
          searchLabel="出库单编号"
          placeholder="请输入出库单编号模糊查询"
          @blur="handleTrim('exwarehouseCode')"
          slot="searchItem2"
        ></el-input>
        <el-input
          v-model="formData.reportInOrgName"
          clearable
          searchLabel="填报单位"
          placeholder="请输入填报单位模糊查询"
          @blur="handleTrim('reportInOrgName')"
          slot="searchItem3"
        ></el-input>
        <el-input
          v-model="formData.warehouseName"
          clearable
          searchLabel="仓库"
          placeholder="请输入仓库模糊查询"
          @blur="handleTrim('warehouseName')"
          slot="searchItem4"
        ></el-input>
        <el-date-picker
          v-model="formData.reportTime"
          clearable
          searchLabel="编制日期"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          slot="searchItem6"
        >
        </el-date-picker>
      </el-search>
    </div>
    <div class="ccui-multifunctional-table-wrapper">
      <el-table
        v-if="tableHack"
        ref="multipleTable"
        :data="tableData"
        :fit="true"
        :row-style="rowClass"
        :cell-style="cellStyle"
        @cell-click="cellClick"
        border
        class="ccui-multifunctional-table"
        @selection-change="handleSelectionChange"
        @header-dragend="tableTitleWidth"
        :min-height="9999"
      >
        <template v-for="(table, index) in tableTheadOptions">
          <el-table-column
            v-if="table.checked"
            :fixed="table.fixed || false"
            :type="table.type"
            :key="index"
            :label="table.label"
            :min-width="table.width"
            :prop="table.prop"
            :filters="table.filters"
            :align="table.align"
            :header-align="table.headerAlign || 'left'"
            :show-overflow-tooltip="true"
          ></el-table-column>
        </template>

        <el-table-column label="操作" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleTurn(scope.row)"
              >撤回</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="ccui-table-footer" v-if="totalNum > 0">
        <div id="ccui-paging">
          <el-pagination
            :total="totalNum"
            :page-size="getLocalPageSize()"
            :current-page="formDataSearch.pageNo"
            :page-sizes="[10, 20, 50, 100, 200, 500]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            popper-class="ccui-paging-page-size-popper"
            @prev-click="handlePrev"
            @next-click="handleNext"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
require("core-js/modules/es.object.assign");
require("core-js/modules/es.object.keys");
require("regenerator-runtime/runtime");
require("core-js/modules/es.object.values");
require("core-js/modules/es.object.set-prototype-of");
require("core-js/modules/es.array.find");
require("core-js/modules/es.array-buffer.is-view");
require("core-js/modules/es.weak-map");
require("core-js/modules/es.promise");
import {
  getDataList,
  getDataTurn,
} from "../api/";
import { setSessionItem, getSessionItem, ishasAgentId } from "@/basa/utils";
export default {
  name: "financialWriteOffListApproval",
  data() {
    return {
      //多页签
      focuses: [
        { focus: "All" },
        { focus: "Submit" },
        { focus: "Approval" },
        { focus: "ApprovalTurn" }
      ],
      isActive: 2,
      // 表格数据
      tableData: [],
      tableHack: true,
      // 表格命名
      tableName: this.tableList.financialWriteOffListApproval,
      // 表格数据
      tableThead: [],
      fixedTableThead: [
        {
          label: "序号",
          prop: "id",
          width: "38",
          checked: true,
          fixed: true,
          type: "index"
        },
        {
          label: "出库单编号",
          prop: "exwarehouseCode",
          width: "150",
          checked: true,
          fixed: true,
          align: "left"
        }
      ],
      // 非锁定表格
      unfixedTableThead: [
        {
          label: "出库单名称",
          prop: "exwarehouseName",
          width: "300",
          checked: true,
          align: "left"
        },
        {
          label: "填报单位",
          prop: "reportInOrgName",
          width: "200",
          checked: true,
          align: "left"
        },
        {
          label: "仓库",
          prop: "warehouseName",
          width: "200",
          checked: true,
          align: "left"
        },
        {
          label: "出库数量",
          prop: "exwarehouseCount",
          width: "100",
          checked: true,
          align: "left"
        },
        {
          label: "出库金额",
          prop: "exwarehouseMoney",
          width: "100",
          checked: true,
          align: "right"
        },
        {
          label: "编制人",
          prop: "reportUsername",
          width: "90",
          checked: true,
          align: "left"
        },
        {
          label: "编制日期",
          prop: "reportTime",
          width: "100",
          checked: true,
          align: "left"
        },
        {
          label: "单据状态",
          prop: "exwarehouseStatusName",
          width: "100",
          checked: true,
          align: "left"
        }
      ],
      //全部数量
      totalNum: 0,
      // 动态表格
      tableTheadOptions: [],
      // 弹框表格
      popoverShow: false,
      selectRow: [],
      selectData: [],
      // 高级搜索数据 start
      // 高级搜索提交数据
      isShowSearch: true,
      formData: {
        reportOrgId: getSessionItem("userInfo", "orgId"),
        labelType:2,
        pageNo: 1,
        pageSize: this.getLocalPageSize(),
        isShowPageLoading: true
      },
      formDataSearch: {
        reportOrgId: getSessionItem("userInfo", "orgId"),
        labelType:2,
        pageNo: 1,
        pageSize: this.getLocalPageSize(),
        isShowPageLoading: true
      },
      // 高级搜索数据 end
    };
  },
  activated() {
    this.getDataList(this.formData);
  },
  mounted() {
    this.initData();
    this.getDataList(this.formData);
  },
  methods: {
    //去空格
    handleTrim(key) {
      if(this.formData[key]){
        this.$set(
          this.formData,
          key,
          this.formData[key].replace(/(^\s*)|(\s*)$/g, "")
        )
      }
    },
    initData() {
      this.setTableWidth();
      this.renderTable();
    },
    getDataList(data) {
      getDataList(data).then(res => {
        if (res.data.code == 0) {
          this.tableData = res.data.data.rows;
          this.tableData.forEach(item => {
            item.exwarehouseStatusName =
              item.exwarehouseStatus == 2
                ? "待提交"
                : item.exwarehouseStatus == 4
                ? "已撤回"
                : item.exwarehouseStatus == 3
                ? "审批中"
                : item.exwarehouseStatus == 5
                ? "审批通过"
                : item.exwarehouseStatus == 6
                ? "审批退回"
                : item.exwarehouseStatus == 21
                ? "冲销中"
                : item.exwarehouseStatus == 22
                ? "已冲销" : "";
            if (
              item.exwarehouseCount ||
              item.exwarehouseCount === 0
            ) {
              item.exwarehouseCount = Number(
                item.exwarehouseCount
              ).toFixed(3);
            }
            if (
              item.exwarehouseMoney ||
              item.exwarehouseMoney === 0
            ) {
              item.exwarehouseMoney = Number(
                item.exwarehouseMoney
              ).toFixed(2);
            }
            if(item.reportTime){
              item.reportTime = item.reportTime.substring(0,10)
            }
          });
          this.totalNum = res.data.data.recordsTotal;
        }
      });
    },
    // 页签跳转
    tabChange(data) {
      this.$router.push({
        path:
          "/inventoryManagement/writeOff/" +
          `List${data}`
      });
    },
    //新增补充协议
    handleGoNew(row) {
      this.$router.push({
        path: "/inventoryManagement/writeOff/Add",
        query:{
          ifAdd:1
        }
      });
    },
    //撤回
    handleTurn(row) {
      this.$confirm("确定要撤回吗?", "提示信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        customClass: "ccui-message-box-custom"
      })
        .then(() => {
          getDataTurn({
            id: row.id
          }).then(res => {
            if (res.data.code == 0) {
              this.$message({
                message: "撤回成功",
                type: "success",
                showClose: true,
                ccuiCustom: true,
                duration: 8000
              });
              this.getDataList(this.formDataSearch);
            }
          });
        })
        .catch(() => {});
    },
    // 查看
    cellClick(row, column, columnIndex) {
      if (row.exwarehouseCode && column.label === "出库单编号") {
        this.$router.push({
          path: "/inventoryManagement/writeOff/Details",
          query: {
            id: row.id,
            ifApprovingStatus: row.exwarehouseStatus
          }
        });
      }
    },
    // 根据返回状态显示不同的文字颜色
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { "background-color": "transparent" };
      }
      if (columnIndex == 1) {
        return { color: "#0089EF", cursor: "pointer" };
      }
    },
    // 默认渲染表格
    renderTable() {
      const localTableData = localStorage.getItem(this.tableName)
        ? JSON.parse(localStorage.getItem(this.tableName))
        : [];
      let unfixedTableThead = this.fixedTableThead.concat(
        this.unfixedTableThead
      );
      let localTableDataStr = localTableData.map(
        ({ label, prop, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );
      let unfixedTableTheadStr = unfixedTableThead.map(
        ({ label, prop, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );

      if (localTableData.length === unfixedTableThead.length) {
        let flag = localTableDataStr.every(item =>
          unfixedTableTheadStr.includes(item)
        );
        if (flag) {
          // 完全相同
          this.tableTheadOptions = localTableData;
          this.tableThead = localTableData;
          localTableData.forEach(item => {
            let index = this.unfixedTableThead.findIndex(
              cItem => item.prop === cItem.prop
            );
            index !== -1 &&
              (this.unfixedTableThead[index].checked = item.checked);
          });
        } else {
          // 长度相同但值不同
          this.tableThead = this.fixedTableThead.concat(this.unfixedTableThead);
          const comment = JSON.stringify(this.tableThead);
          localStorage.setItem(this.tableName, comment);
          const localTableData = JSON.parse(
            localStorage.getItem(this.tableName)
          );
          this.tableTheadOptions = localTableData;
        }
      } else {
        // 长度不同
        this.tableThead = this.fixedTableThead.concat(this.unfixedTableThead);
        const comment = JSON.stringify(this.tableThead);
        localStorage.setItem(this.tableName, comment);
        const localTableData = JSON.parse(localStorage.getItem(this.tableName));
        this.tableTheadOptions = localTableData;
      }
    },
    // 渲染本地存储表格宽度
    setTableWidth() {
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      if (localTableData) {
        for (let i = 0; i < this.tableTheadOptions.length; i++) {
          if (this.tableTheadOptions[i].label === localTableData[i].label) {
            this.tableTheadOptions[i].width = localTableData[i].width;
          }
        }
      }
    },
    // 表格宽度更改存入
    tableTitleWidth(newWidth, oldWidth, column, event) {
      for (let i = 0; i < this.unfixedTableThead.length; i++) {
        if (this.unfixedTableThead[i].label === column.label) {
          this.unfixedTableThead[i].width = newWidth;
        }
      }
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      this.tableTheadOptions = JSON.parse(localStorage.getItem(this.tableName));
      this.tableHack = false;
      this.$nextTick(() => {
        this.tableHack = true;
      });
    },
    handleSelectionChange(data) {
      this.selectData = data;
    },
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { "background-color": "rgba(255,232,195,1) " };
      }
    },
    // 分页
    // 上一页
    handlePrev() {},
    // 下一页
    handleNext() {},
    //  显示条数更改
    handleSizeChange(val) {
      this.formDataSearch.pageNo = 1;
      this.formDataSearch.pageSize = val;
      setSessionItem("pageSize", this.tableName, val);
      this.getDataList(this.formDataSearch);
    },
    // 获取默认条数
    getLocalPageSize() {
      return (
        getSessionItem("pageSize", this.tableList.financialWriteOffListApproval) || 10
      );
    },
    // 当前页码更改
    handleCurrentChange(val) {
      // 跳转翻页都会调这个方法
      this.formDataSearch.pageNo = val;
      this.getDataList(this.formDataSearch);
    },
    // 分页 end
    // 高级搜索所需函数 start
    // 高级搜索展开按钮
    search(searchData) {
     this.formDataSearch = JSON.parse(JSON.stringify(searchData));
      this.formDataSearch.reportOrgId = getSessionItem("userInfo", "orgId");
      this.formDataSearch.pageNo = 1;
      this.formDataSearch.isShowPageLoading = true;
      this.formDataSearch.labelType = 2
      if(this.formDataSearch.reportTime){
        this.formDataSearch.reportTimeStart = new Date(this.formDataSearch.reportTime[0].replace(/-/g,"/")).getTime()
        this.formDataSearch.reportTimeEnd = new Date(this.formDataSearch.reportTime[1].replace(/-/g,"/")).getTime()
      }
      this.formDataSearch.pageSize = this.getLocalPageSize();
      this.getDataList(this.formDataSearch);
    }
    // 高级搜索 end
  },
  beforeRouteLeave(to, from, next) {
    for (var key in this.$vnode.parent.parent.componentInstance.cache) {
      delete this.$vnode.parent.parent.componentInstance.cache[
        ishasAgentId(to.path, key)
      ];
    }
    next();
  }
};
</script>
<style lang="scss" scoped>
/deep/ #ccui-paging .ccui-pagination-btn {
  display: block;
}
/deep/ .el-searchs-box {
  width: 405px !important;
}
/deep/
  .ccui-advanced-search-wrapper
  .el-search
  .ccui-search-wrapper
  .el-searchs
  .el-searchs-right
  .el-date-editor {
  padding-right: 0px !important;
}
</style>
